package com.xunji.user.service.impl;

import com.xunji.user.service.CacheService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class MemCacheServiceImpl implements CacheService {

    private static final ConcurrentHashMap<String,Val> CACHE = new ConcurrentHashMap<>();

    private static final long  DEFAULT_TTL = 1000 * 60 *60L;



    @Override
    public <T> T get(String key, Class T) {
        Val val = CACHE.get(key);
        if(val == null ){
            return null;
        }
        if(val.getExpireTime() <= System.currentTimeMillis()){
            CACHE.remove(key);
            return null;
        }
        T value = null;
        try {
            value = (T)val.getValue();
        } catch (Exception e) {
            log.error("查询缓存错误,key={}",key,e);
        }
        return value;
    }

    @Override
    public boolean set(String key, Object val, long ttl) {
        if(val == null) return false;
        CACHE.put(key,new Val(val,ttl));
        return true;
    }

    @Override
    public boolean set(String key, Object val) {
        if(val == null) return false;
        CACHE.put(key,new Val(val,DEFAULT_TTL));
        return true;
    }

    @Override
    public boolean remove(String key) {
        return false;
    }

    @Override
    public boolean isExist(String key) {
        Val val = CACHE.get(key);
        if(val == null || val.getExpireTime() <= System.currentTimeMillis()){
            CACHE.remove(key);
            return false;
        }
        return true;
    }

    @Data
    public
    class Val{
        private Object value;

        private long ttl;

        private long iniTime;

        private long expireTime;

        public Val(Object value,long ttl){
            this.ttl = ttl;
            this.value = value;
            this.iniTime = System.currentTimeMillis();
            this.expireTime = this.iniTime + this.ttl;
        }
    }

    public static void refresh(){
        log.info("刷新内存缓存");
        Iterator<Map.Entry<String, Val>> iterator = CACHE.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Val> next = iterator.next();
            Val value = next.getValue();
            long now = System.currentTimeMillis();
            if (value.getExpireTime() < now){
                iterator.remove();
            }
        }
    }
}
